import express from 'express';
import mysql from 'mysql2/promise';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import multer from 'multer';

const app = express();
app.use(cors());
app.use(express.json());

// 文件上传配置
const storage = multer.diskStorage({
  destination: path.join('D:', '音乐中枢', 'Songs'),
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});
const upload = multer({ storage, limits: { fileSize: 50 * 1024 * 1024 } });

// 数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'musiccenter',
  connectionLimit: 10,
});

// 权限验证中间件
const requireAdmin = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    console.log('权限验证 - 收到token:', token); // 调试日志
    
    if (!token) {
      console.log('权限验证 - 缺少token'); // 调试日志
      return res.status(401).json({ error: '未授权' });
    }

    const [user] = await pool.query(
      'SELECT * FROM users WHERE token = ? AND is_admin = 1', // 仅查询管理员
      [token]
    );
    
    console.log('权限验证 - 查询到用户:', user); // 调试日志
    
    if (user.length === 0) {
      console.log('权限验证 - 用户非管理员或不存在'); // 调试日志
      return res.status(403).json({ error: '权限不足' });
    }
    
    req.adminUser = user[0];
    next();
  } catch (error) {
    console.error('权限验证错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
};

// 统一登录接口
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json({ error: '请提供用户名和密码' });
  }

  try {
    const [users] = await pool.query(
      'SELECT id, username, token, is_admin FROM users WHERE username = ? AND password = ?',
      [username, password]
    );
    
    if (users.length === 0) {
      return res.status(401).json({ error: '认证失败' });
    }
    
    res.json({ user: users[0] });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 统计数据接口
// app.get('/api/stats', requireAdmin, async (req, res) => {
//   try {
//     const [totalSongs] = await pool.query('SELECT COUNT(*) AS count FROM songs');
//     const [totalUsers] = await pool.query('SELECT COUNT(*) AS count FROM users');
//     const [todayUploads] = await pool.query(
//       'SELECT COUNT(*) AS count FROM songs WHERE DATE(created_at) = CURDATE()'
//     );
    
//     res.json({
//       totalSongs: totalSongs[0].count,
//       totalUsers: totalUsers[0].count,
//       todayUploads: todayUploads[0].count
//     });
//   } catch (error) {
//     console.error('统计数据错误:', error);
//     res.status(500).json({ error: '服务器错误' });
//   }
// });

// 歌曲管理接口
app.get('/api/songs', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT id, songtitle, songauthor FROM songs'); // 移除 created_at
    res.json(rows);
  } catch (error) {
    console.error('歌曲列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

app.post('/api/songs', requireAdmin, upload.single('file'), async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '请选择上传文件' });
  }

  const { title, artist } = req.body;
  if (!title || !artist) {
    return res.status(400).json({ error: '请填写歌曲名称和歌手' });
  }

  try {
    console.log('准备上传歌曲:', title, 'by', artist);
    console.log('上传的文件:', req.file);
    
    await pool.query(
  'INSERT INTO songs (songtitle, songauthor, songpath) VALUES ($1, $2, $3)',
  [title, artist, req.file.filename]
);
    
    res.status(201).json({ message: '歌曲上传成功' });
  } catch (error) {
    console.error('歌曲上传错误:', error);
    // 记录详细的错误堆栈
    console.error('错误堆栈:', error.stack);
    
    // 区分不同类型的错误
    if (error.code === 'ENOENT') {
      res.status(500).json({ error: '文件存储路径不存在，请检查服务器配置' });
    } else if (error.code === 'EPERM') {
      res.status(500).json({ error: '没有写入权限，请检查服务器目录权限' });
    } else {
      res.status(500).json({ error: '服务器内部错误，请稍后重试' });
    }
  }
});

app.delete('/api/songs/:id', requireAdmin, async (req, res) => {
  const songId = req.params.id;
  
  try {
    const [song] = await pool.query('SELECT songpath FROM songs WHERE id = ?', [songId]);
    if (song.length === 0) return res.status(404).json({ error: '歌曲不存在' });

    await pool.query('DELETE FROM songs WHERE id = ?', [songId]);
    
    const filePath = path.join('D:', '音乐中枢', 'Songs', song[0].songpath);
    fs.unlinkSync(filePath);
    
    res.json({ message: '歌曲删除成功' });
  } catch (error) {
    console.error('歌曲删除错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 用户管理接口
app.get('/api/users', requireAdmin, async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT id, username, email, phone FROM users'); // 移除 created_at
    res.json(rows);
  } catch (error) {
    console.error('用户列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

app.delete('/api/users/:id', requireAdmin, async (req, res) => {
  const userId = req.params.id;
  
  try {
    if (userId === '1') {
      return res.status(403).json({ error: '禁止删除超级管理员' });
    }
    
    await pool.query('DELETE FROM users WHERE id = ?', [userId]);
    res.json({ message: '用户删除成功' });
  } catch (error) {
    console.error('用户删除错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 用户收藏相关接口
app.get('/api/usersongs/check/:songId', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  const songId = req.params.songId;
  
  if (!token) {
    return res.status(401).json({ error: '未授权' });
  }

  try {
    const [rows] = await pool.query(
      'SELECT * FROM usersongs WHERE usertoken = ? AND id = ?',
      [token, songId]
    );
    res.json({ isLiked: rows.length > 0 });
  } catch (error) {
    res.status(500).json({ error: '数据库查询失败' });
  }
});

app.get('/api/usersongs', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: '未授权' });
  }

  try {
    const [rows] = await pool.query(
      'SELECT * FROM usersongs WHERE usertoken = ?',
      [token]
    );
    res.json(rows);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '数据库查询失败' });
  }
});

app.post('/api/usersongs', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  const { songId, songTitle, songAuthor, songPath } = req.body;

  if (!token) {
    return res.status(401).json({ error: '未授权' });
  }

  try {
    const [existing] = await pool.query(
      'SELECT * FROM usersongs WHERE usertoken = ? AND id = ?',
      [token, songId]
    );

    if (existing.length > 0) {
      return res.status(409).json({ error: '已收藏该歌曲' });
    }

    await pool.query(
      'INSERT INTO usersongs (id, songtitle, songauthor, songpath, usertoken) VALUES (?, ?, ?, ?, ?)',
      [songId, songTitle, songAuthor, songPath, token]
    );

    res.status(201).json({ message: '收藏成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '数据库操作失败' });
  }
});

app.delete('/api/usersongs/:songId', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  const songId = req.params.songId;

  if (!token) {
    return res.status(401).json({ error: '未授权' });
  }

  try {
    const [result] = await pool.query(
      'DELETE FROM usersongs WHERE usertoken = ? AND id = ?',
      [token, songId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '未找到收藏记录' });
    }

    res.json({ message: '取消收藏成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '数据库操作失败' });
  }
});

// 音乐详情接口
app.get('/api/music/:id', async (req, res) => {
  const musicId = req.params.id;
  const sql = `SELECT songtitle, songauthor, songpath FROM songs WHERE id = ?`;

  try {
    const [rows] = await pool.execute(sql, [musicId]);
    if (rows.length > 0) {
      res.json(rows[0]);
    } else {
      res.status(404).send('歌曲未找到');
    }
  } catch (error) {
    console.error('查询错误:', error);
    res.status(500).send('数据获取失败');
  }
});

// 音频文件路由
app.get('/api/songs/:filename', (req, res) => {
  const filename = req.params.filename;
  const safeFilename = path.basename(filename);
  const songPath = path.join('D:', '音乐中枢', 'Songs', safeFilename);

  console.log('音频文件请求路径:', songPath);

  if (!fs.existsSync(songPath)) {
    return res.status(404).send('文件未找到');
  }

  res.set('Cache-Control', 'public, max-age=3600');
  
  const stream = fs.createReadStream(songPath);
  stream.on('error', (err) => {
    if (err.code === 'ENOENT') {
      res.status(404).send('文件不存在');
    } else {
      console.error('流式传输错误:', err);
      res.status(500).send('服务器错误');
    }
  });
  
  stream.pipe(res);
});

//歌单
app.get('/api/playlist/:id', async (req, res) => {
  const playlistId = req.params.id;
  const sql = `SELECT * FROM recommended WHERE id = ?`;

  try {
    const [rows] = await pool.execute(sql, [playlistId]);
    if (rows.length > 0) {
      res.json(rows[0]);
    } else {
      res.status(404).send('歌单未找到');
    }
  } catch (error) {
    console.error('查询错误:', error);
    res.status(500).send('数据获取失败');
  }
});

// 推荐歌单接口
app.get('/api/recommended', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM recommended');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

// 用户注册接口
app.post('/api/register', async (req, res) => {
  const { username, password, phone, email, token } = req.body;

  if (!username || !password || !phone || !email) {
    return res.status(400).json({ error: '所有字段必须填写' });
  }

  try {
    const [userExist] = await pool.query('SELECT username FROM users WHERE username = ?', [username]);
    if (userExist.length > 0) {
      return res.status(409).json({ error: '用户名已存在' });
    }

    const [emailExist] = await pool.query('SELECT email FROM users WHERE email = ?', [email]);
    if (emailExist.length > 0) {
      return res.status(409).json({ error: '邮箱已注册' });
    }

    const [phoneExist] = await pool.query('SELECT phone FROM users WHERE phone = ?', [phone]);
    if (phoneExist.length > 0) {
      return res.status(409).json({ error: '手机号已注册' });
    }

    const [result] = await pool.query(
      'INSERT INTO users (username, password, email, phone, token) VALUES (?, ?, ?, ?, ?)',
      [username, password, email, phone, token]
    );

    console.log('插入结果:', result);
    res.status(201).json({ 
      message: '注册成功',
      userId: result.insertId 
    });
  } catch (error) {
    console.error('完整错误堆栈:', error.stack);
    res.status(500).json({ 
      error: `数据库操作失败: ${error.message}` 
    });
  }
});

// MV相关接口
app.get('/api/mvlist', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM mvlist');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/mvlist/:id', async (req, res) => {
  const playlistId = req.params.id;
  const sql = `SELECT * FROM mvlist WHERE id = ?`;

  try {
    const [rows] = await pool.execute(sql, [playlistId]);
    if (rows.length > 0) {
      res.json(rows[0]);
    } else {
      res.status(404).send('歌单未找到');
    }
  } catch (error) {
    console.error('查询错误:', error);
    res.status(500).send('数据获取失败');
  }
});

app.get('/api/mv/:filename', (req, res) => {
  const filename = req.params.filename;
  const safeFilename = path.basename(filename);
  const mvPath = path.join('D:', '音乐中枢', 'mv', safeFilename);

  console.log('MV文件请求路径:', mvPath);

  if (!fs.existsSync(mvPath)) {
    return res.status(404).send('MV文件未找到');
  }

  res.set('Cache-Control', 'public, max-age=3600');
  
  const stream = fs.createReadStream(mvPath);
  stream.on('error', (err) => {
    if (err.code === 'ENOENT') {
      res.status(404).send('文件不存在');
    } else {
      console.error('流式传输错误:', err);
      res.status(500).send('服务器错误');
    }
  });
  
  stream.pipe(res);
});

// 排行榜相关接口
app.get('/api/hotranking', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM hotranking');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/oldranking', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM oldranking');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/europeranking', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM europeranking');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/korearanking', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM korearanking');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/newranking', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM newranking');
    res.json(rows);
  } catch (error) {
    console.error('数据库查询出错:', error.message);
    res.status(500).json({ error: error.message });
  }
});

// 启动服务器
app.listen(3001, () => {
  console.log('Server running on port 3001');
});